<template>
  <div class="gray-page resident-detail-page">
    <nav-bar :title="`宠物基础信息${title}`"></nav-bar>
    <div class="resident-detail-main page-main">
      <van-sticky class="page-scroll" :offset-top="44">
        <van-form
          validate-trigger="onSubmit"
          :show-error="false"
          ref="from"
          input-align="right"
          error-message-align="right"
          :label-width="120"
          @failed="onFailed"
          @submit="onSubmit"
        >
          <van-collapse v-model="activeNames">
            <van-collapse-item size="large" title="基础信息" name="1">
              <van-field
                required
                name="petName"
                v-model="formParams.petName"
                label="宠物姓名"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :maxlength="50"
                :rules="rules.petName"
              />
              <van-field
                required
                name="petType"
                v-model="formParams.petType"
                label="宠物品种"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :maxlength="50"
                :rules="rules.petType"
              />
              <van-field
                required
                readonly
                clickable
                name="petSexName"
                v-model="formParams.petSexName"
                label="宠物性别"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.petSexName"
                @click="dictOpenPopup('petSex')"
              />
              <van-field
                required
                name="petColor"
                v-model="formParams.petColor"
                label="毛色"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :maxlength="20"
                :rules="rules.petColor"
              />
              <van-field
                name="petAge"
                v-model="formParams.petAge"
                label="宠物年龄"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :maxlength="20"
              />
              <van-field
                required
                readonly
                clickable
                name="vaccineInjectionName"
                v-model="formParams.vaccineInjectionName"
                label="疫苗注射情况"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.vaccineInjectionName"
                @click="dictOpenPopup('vaccineInjection')"
              />
              <van-field
                name="licence"
                v-model="formParams.licence"
                label="许可证号"
                right-icon="arrow"
                placeholder="请输入"
                class="van-field__right-icon-white"
                :maxlength="20"
              />
              <van-field
                name="issuedAuthority"
                v-model="formParams.issuedAuthority"
                label="发证机关"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :maxlength="50"
              />
              <van-field
                readonly
                clickable
                name="issuedTime"
                v-model="formParams.issuedTime"
                label="发证日期"
                placeholder="请选择"
                right-icon="arrow"
                @click="dateOpenPopup('issuedTime')"
              />
              <van-field
                required
                readonly
                clickable
                name="regionCodeName"
                v-model="formParams.regionCodeName"
                label="所属场所"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.regionCodeName"
                @click="placePopupShow = true"
              />
            </van-collapse-item>
            <van-collapse-item size="large" title="主人信息" name="2">
              <van-field
                required
                name="owner"
                v-model="formParams.owner"
                label="主人姓名"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :maxlength="50"
                :rules="rules.owner"
              />
              <van-field
                required
                name="phone"
                v-model="formParams.phone"
                label="联系方式"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :rules="rules.phone"
              />
              <van-field
                required
                readonly
                clickable
                name="idTypeName"
                v-model="formParams.idTypeName"
                label="证件类型"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.idTypeName"
                @click="dictOpenPopup('idType')"
              />
              <van-field
                required
                name="idCard"
                v-model="formParams.idCard"
                label="证件号码"
                placeholder="请选择"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :rules="formParams.idType === '111' ? rules.idCard : rules.passport"
              />
              <van-field
                required
                name="address"
                v-model="formParams.address"
                label="居住地址"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :maxlength="100"
                :rules="rules.address"
              />
              <van-field readonly required :label-width="300" :border="false">
                <template #label>
                  <span>上传照片</span>
                  <span class="van-field__label--tip">（登记犬只侧面全身照片）</span>
                </template>
              </van-field>
              <van-field
                class="van-field__value--upload"
                input-align="left"
                error-message-align="left"
                :rules="rules.fileList"
              >
                <template #input>
                  <van-uploader
                    name="fileList"
                    v-model="fileList"
                    accept="image/*"
                    :preview-image="false"
                    :max-size="maxSize"
                    :before-read="uploadBeforeRead"
                    :after-read="uploadAfterRead"
                  >
                    <div class="van-uploader__input--yellow-small">
                      <van-image
                        v-if="fileList.length"
                        width="82px"
                        height="102px"
                        fit="cover"
                        style="border-radius: 12px"
                        :src="
                          fileList[fileList.length - 1].content || $config.ImageURl + fileList[fileList.length - 1].url
                        "
                      />
                      <template v-else>
                        <div class="upload-image"><van-icon class="iconImg" name="plus" size="16" /></div>
                        <div class="upload-text">不超过1M</div>
                      </template>
                    </div>
                  </van-uploader>
                </template>
              </van-field>
            </van-collapse-item>
          </van-collapse>
          <div style="padding: 16px">
            <template v-if="$route.query.type === 'Update'">
              <van-button block type="info" native-type="submit" :disabled="buttonDisabled">更新</van-button>
            </template>
            <template v-else-if="$route.query.type === 'Approve'">
              <van-row :gutter="20">
                <van-col :span="12">
                  <van-button
                    block
                    native-type="button"
                    @click="
                      $router.push(`/resident/audit/reject?code=${formParams.code}&baseType=${$route.query.baseType}`)
                    "
                  >
                    驳回
                  </van-button>
                </van-col>
                <van-col :span="12">
                  <van-button block type="info" native-type="submit" :disabled="buttonDisabled">通过</van-button>
                </van-col>
              </van-row>
            </template>
            <template v-else>
              <van-button block type="info" native-type="submit" :disabled="buttonDisabled">提交</van-button>
            </template>
          </div>
        </van-form>
      </van-sticky>
    </div>
    <!-- 字典项 -->
    <van-popup v-model="dictPopupShow" round position="bottom" @close="dictValue = ''">
      <van-picker
        show-toolbar
        :default-index="dictData[dictType] && dictData[dictType].findIndex(o => o.code === dictValue)"
        :columns="dictData[dictType]"
        value-key="description"
        @cancel="dictPopupShow = false"
        @confirm="dictOnConfirm"
      />
    </van-popup>
    <!-- 日期 -->
    <van-popup v-model="datePopupShow" round position="bottom" @close="date = new Date()">
      <van-datetime-picker
        v-model="date"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        :formatter="formatter"
        @cancel="datePopupShow = false"
        @confirm="dateOnConfirm"
      />
    </van-popup>
    <!-- 所属场所 -->
    <van-popup v-model="placePopupShow" round position="bottom">
      <van-picker
        show-toolbar
        :columns="placeData"
        value-key="title"
        @cancel="placePopupShow = false"
        @confirm="placeOnConfirm"
      />
    </van-popup>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import Upload from '@/mixins/upload'
import SelectPopup from '@/mixins/selectPopup'
import General from '@/api/general'
import Resident from '@/api/resident'
import { FormParams } from './libs/pet'
import { residentNameReg, idCardCheck, phoneReg, passPortCardReg } from '@/libs/regexp'
export default {
  mixins: [Upload, SelectPopup],
  data() {
    return {
      title: '采集',
      activeNames: ['1', '2'],
      folder: 'approve/pet',
      maxSize: 1024 * 1024,
      fileList: [],
      dictTypes: 'petSex,vaccineInjection,idType',
      placeData: [],
      placePopupShow: false,

      buttonDisabled: false,
      formParams: new FormParams(),
      rules: {
        petName: [{ required: true, message: '请输入宠物姓名' }],
        petType: [{ required: true, message: '请输入宠物品种' }],
        petSexName: [{ required: true, message: '请选择性别' }],
        petColor: [{ required: true, message: '请输入毛色' }],
        vaccineInjectionName: [{ required: true, message: '请选择疫苗注射情况' }],
        regionCodeName: [{ required: true, message: '请选择所属场所' }],
        fileList: [{ required: true, message: '请上传照片' }],
        owner: [
          { required: true, message: '请输入主人姓名' },
          { pattern: residentNameReg, message: '请输入中文、英文和"·"' }
        ],
        phone: [
          { required: true, message: '请输入联系方式' },
          { pattern: phoneReg, message: '请输入正确的手机号' }
        ],
        idTypeName: [{ required: true, message: '请选择证件类型' }],
        idCard: [
          { required: true, message: '请输入证件号' },
          { validator: idCardCheck, message: '请输入正确的证件号' }
        ],
        passport: [
          { required: true, message: '请输入证件号' },
          { pattern: passPortCardReg, message: '请输入正确的证件号' }
        ],
        address: [{ required: true, message: '请输入居住地址' }]
      }
    }
  },
  computed: {
    ...mapState({
      user: state => state.userInfo
    })
  },
  created() {
    // 字典项
    this.getDict(this.dictTypes)
    // 场所
    this.getPlace()

    // 更新
    if (this.$route.query.code) {
      this.title = this.$route.query.type === 'Update' ? '更新' : '审核'
      this.getDetail()
    }
  },
  methods: {
    // 获取详情
    getDetail() {
      Resident.BaseInfo.petDetail({
        code: this.$route.query.code,
        queryType: this.$route.query.queryType
      }).then(res => {
        const { status, data } = res.data
        if (status === 0) {
          this.formParams = { ...data }
          this.formParams.vaccineInjection = this.formParams.vaccinationStatus
          this.formParams.vaccineInjectionName = data.vaccinationStatusName
          if (this.formParams.imageUrl) {
            this.fileList = [
              {
                url: this.formParams.imageUrl
              }
            ]
          }
        }
      })
    },
    // 获取场所
    getPlace() {
      General.Region.getPlace({
        regionCode: this.user.regionCode
      }).then(res => {
        const { data, status } = res.data
        if (status === 0) {
          this.placeData = data
        }
      })
    },
    // 场所 - 确认
    placeOnConfirm(item) {
      this.formParams.regionCode = item.code
      this.formParams.regionCodeName = item.title
      this.placePopupShow = false
    },
    // 表单 - 校验
    onFailed(errorInfo) {
      this.$refs.from.scrollToField(errorInfo.errors[0].name)
    },
    // 表单 - 提交
    onSubmit() {
      this.buttonDisabled = true
      this.formParams.vaccinationStatus = this.formParams.vaccineInjection
      this.formParams.imageUrl = this.fileList[this.fileList.length - 1].url
      Resident.BaseInfo[`pet${this.$route.query.type || 'Save'}`](this.formParams)
        .then(res => {
          const { status } = res.data
          if (status === 0) {
            this.$router.push({
              path: '/page/message',
              query: {
                backTo: this.$route.query.type ? '-2' : '-1',
                title: this.$route.query.type ? `${this.title}成功` : '提交成功'
              }
            })
          } else {
            this.$toast.fail(res.data.message)
          }
          this.buttonDisabled = false
        })
        .catch(() => {
          this.buttonDisabled = false
        })
    }
  }
}
</script>
<style lang="less" scoped>
@import '~@/assets/style/resident/detail.less';
</style>
